let keywords = [];

// 加载保存的关键字
async function loadKeywords() {
  try {
    const result = await chrome.storage.sync.get('keywords');
    keywords = result.keywords || [];
    updateKeywordsList();
  } catch (error) {
    console.error('加载关键字失败:', error);
    // 如果同步存储失败，回退到本地存储
    const local = await chrome.storage.local.get('keywords');
    keywords = local.keywords || [];
    updateKeywordsList();
  }
}

// 更新关键字列表显示
function updateKeywordsList() {
  const list = document.getElementById('keywords-list');
  list.innerHTML = '';
  
  if (keywords.length === 0) {
    list.innerHTML = '<div class="no-keywords">暂无保存的关键字</div>';
    return;
  }

  keywords.forEach((item, index) => {
    const div = document.createElement('div');
    div.className = 'keyword-item';
    div.innerHTML = `
      <span class="keyword-text" style="background-color: ${item.color}">${item.text}</span>
      <div class="keyword-actions">
        <span class="use-keyword" data-index="${index}" title="使用此关键字">✓</span>
        <span class="remove-keyword" data-index="${index}" title="删除">×</span>
      </div>
    `;
    list.appendChild(div);
  });
}

// 保存关键字到存储
async function saveKeywords() {
  try {
    await chrome.storage.sync.set({ keywords });
  } catch (error) {
    console.error('同步保存失败，使用本地存储:', error);
    // 如果同步存储失败，保存到本地
    await chrome.storage.local.set({ keywords });
  }
}

document.getElementById('highlight').addEventListener('click', async () => {
  const keyword = document.getElementById('keyword').value.trim();
  const color = document.getElementById('highlightColor').value;
  
  if (!keyword) {
    alert('请输入关键字！');
    return;
  }

  // 检查是否已存在相同关键字
  const existingIndex = keywords.findIndex(k => k.text === keyword);
  if (existingIndex !== -1) {
    // 更新现有关键字的颜色
    keywords[existingIndex].color = color;
  } else {
    // 添加新关键字
    keywords.unshift({ text: keyword, color }); // 新关键字添加到列表开头
    // 限制保存的关键字数量
    if (keywords.length > 50) {
      keywords.pop();
    }
  }
  
  await saveKeywords();
  updateKeywordsList();

  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  const response = await chrome.tabs.sendMessage(tab.id, { 
    action: 'highlight', 
    keyword,
    color
  });

  updateMatchCount(response.totalMatches);
  document.getElementById('keyword').value = '';
});

document.getElementById('nextMatch').addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  const color = document.getElementById('highlightColor').value;
  const response = await chrome.tabs.sendMessage(tab.id, { 
    action: 'nextMatch',
    color // 传递当前选择的颜色
  });
  if (response) {
    updateMatchCount(response.totalMatches, response.currentMatchIndex);
  }
});

document.getElementById('prevMatch').addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  const color = document.getElementById('highlightColor').value;
  const response = await chrome.tabs.sendMessage(tab.id, { 
    action: 'prevMatch',
    color // 传递当前选择的颜色
  });
  if (response) {
    updateMatchCount(response.totalMatches, response.currentMatchIndex);
  }
});

function updateMatchCount(total, current = 0, type = '') {
  const matchCountEl = document.getElementById('matchCount');
  if (total > 0) {
    matchCountEl.textContent = type ? 
      `${current + 1} / ${total} 个匹配 (${type})` :
      `${current + 1} / ${total} 个匹配`;
  } else {
    matchCountEl.textContent = '没有找到匹配项';
  }
}

document.getElementById('clear').addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  chrome.tabs.sendMessage(tab.id, { action: 'clearHighlights' });
  keywords = [];
  await saveKeywords();
  updateKeywordsList();
});

// 添加关键字列表的点击事件处理
document.getElementById('keywords-list').addEventListener('click', async (e) => {
  const index = parseInt(e.target.dataset.index);
  
  if (e.target.classList.contains('remove-keyword')) {
    keywords.splice(index, 1);
    await saveKeywords();
    updateKeywordsList();
  } else if (e.target.classList.contains('use-keyword')) {
    const keyword = keywords[index];
    document.getElementById('keyword').value = keyword.text;
    document.getElementById('highlightColor').value = keyword.color;
    
    // 自动触发高亮
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    const response = await chrome.tabs.sendMessage(tab.id, { 
      action: 'highlight', 
      keyword: keyword.text,
      color: keyword.color
    });
    updateMatchCount(response.totalMatches);
  }
});

document.getElementById('autoHighlight').addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  const response = await chrome.tabs.sendMessage(tab.id, { 
    action: 'highlight',
    autoHighlight: true
  });
  updateMatchCount(response.totalMatches);
});

// 添加消息监听器
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'updateCount') {
    updateMatchCount(request.total, request.current, request.type);
  }
});

// 初始化加载
document.addEventListener('DOMContentLoaded', loadKeywords); 